package com.sinosoft.web.easyui.api;

import com.sinosoft.hydra.logging.LogModules;
import cn.com.sinux.spring.commons.PropertyCollection;
import com.sinosoft.hydra.um.condition.SearchRoleCondition;
import com.sinosoft.hydra.um.domain.permission.SysResource;
import com.sinosoft.hydra.um.domain.permission.SysRole;
import com.sinosoft.hydra.um.domain.permission.SysUserMember;
import com.sinosoft.hydra.um.helper.LoggerHelper;
import com.sinosoft.hydra.um.services.SysRoleService;
import cn.com.sinux.spring.utils.BeanUtils;
import cn.com.sinux.spring.utils.PageUtils;
import cn.com.sinux.spring.json.JsonFilter;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.text.ParseException;
import java.util.LinkedList;
import java.util.List;

/**
 * 角色控制器，负责角色分配
 * 模块注册
 *
 * @author Zhengt@sinux.com.cn
 * @author chendl
 * @time 2015-2-1
 * @desc 一些供角色调用的服务
 */
@Controller
@RequestMapping("api/role")
public class SysRoleApi {

    /**
     * 角色的service层SysRoleService
     */
    @Autowired
    private SysRoleService roleService;

    /**
     * 跳转角色的list页面
     *
     * @return 角色页面
     */
    @RequestMapping("gotoRolePage")
    @RequiresPermissions(value = "role:data:list")
    public String gotoquerypage() {
//        LoggerHelper.logInfo("查询了角色列表信息");
        return "hydra_easyui/role/index";
    }


    /**
     * 跳转角色的添加页面
     *
     * @return 角色页面
     */
    @RequestMapping("toAdd")
    @RequiresPermissions(value = "role:data:add")
    public String toAdd() {
        return "hydra_easyui/role/addRole";
    }


    /**
     * 跳转角色的修改页面
     *
     * @return 角色页面
     */
    @RequestMapping("toUpdate")
    @RequiresPermissions(value = "role:data:update")
    public String toUpdate(Model model, @RequestParam(required = true) String id) {
        SysRole role = roleService.findOne(id);
        model.addAttribute("role", role);
        return "hydra_easyui/role/updateRole";
    }


    /**
     * 跳转角色的搜索页面
     *
     * @return 角色页面
     */
    @RequestMapping("search")
    public String search(Model model) {
        return "hydra_easyui/role/search";
    }


    /**
     * 跳转角色的list页面
     *
     * @return 角色页面
     */
    @RequestMapping("toResTree")
    @RequiresPermissions(value = "role:permission:add")
    public String toResTree(Model model, @RequestParam(required = true) String id) {
        model.addAttribute("role", roleService.findOne(id));
        return "hydra_easyui/role/resTree";
    }

    /**
     * 跳转角色的list页面
     *
     * @return 角色页面
     */
    @RequestMapping("toUserTree")
    @RequiresPermissions(value = "role:user:add")
    public String toUserTree(Model model, @RequestParam(required = true) String id) {
        SysRole role = roleService.findOne(id);
        model.addAttribute("role", role);
        List<String> userIds = new LinkedList<String>();
        for (SysUserMember sysUserMember : role.getSysUserMembers()) {
            userIds.add(sysUserMember.getId());
        }
        model.addAttribute("roleUserIds", StringUtils.join(userIds, ","));
        return "hydra_easyui/role/userTree";
    }

    /**
     * ajax保存角色
     *
     * @param role 角色基本信息 id为空位新增
     * @return 返回操作结果
     * @throws java.text.ParseException
     */
    @RequestMapping(value = "saveForJson", method = RequestMethod.POST)
    @RequiresPermissions(value = "role:data:add")
    @ResponseBody
    public Object addForJson(SysRole role)
            throws ParseException {
        SysRole result = roleService.addRole(role);
        LoggerHelper.logInfo("新增了角色‘{}’", role.getRoleName());
        return JsonFilter.doPropertyFilter(result, new PropertyCollection()
                .addProperties(SysRole.class, "id", "roleName"));
    }

    /**
     * 保存角色的资源
     *
     * @param searchRoleCondition
     * @return
     */
    @RequestMapping(value = "saveRoleResources", method = RequestMethod.POST)
    @RequiresPermissions(value = "role:permission:add")
    @ResponseBody
    public Object saveRoleResources(SearchRoleCondition searchRoleCondition) {
        SysRole result = roleService.saveRoleResources(searchRoleCondition.getId(), searchRoleCondition.getResources());
        LoggerFactory.getLogger(LogModules.TRACE_LOGGER).info("修改了角色‘{}’资源：", result.getRoleName());
        LoggerHelper.logInfo("修改了角色‘{}’的资源{}", result.getRoleName(), new LoggerHelper.PropertyReader<SysResource>(result.getSysResources(),
                "resourceName"));
        return JsonFilter.doPropertyFilter(result, new PropertyCollection()
                .addProperties(SysRole.class, "id", "roleName"));
    }

    /**
     * 保存角色的用户
     *
     * @param searchRoleCondition
     * @return
     */
    @RequestMapping(value = "saveRoleUsers", method = RequestMethod.POST)
    @RequiresPermissions(value = "role:user:add")
    @ResponseBody
    public Object saveRoleUsers(SearchRoleCondition searchRoleCondition) {
        SysRole result = roleService.saveRoleUsers(searchRoleCondition.getId(), searchRoleCondition.getUserIds());
        LoggerHelper.logInfo("修改角色‘{}’用户：", result.getRoleName(), new LoggerHelper.PropertyReader<SysUserMember>(result.getSysUserMembers(),
                "userName"));
        return JsonFilter.doPropertyFilter(result, new PropertyCollection()
                .addProperties(SysRole.class, "id", "roleName"));
    }

    /**
     * 修改角色的信息
     *
     * @param role 角色基本信息 id为空位新增
     * @return 返回操作结果
     * @throws java.text.ParseException
     */
    @RequestMapping(value = "updateForJson", method = RequestMethod.POST)
    @RequiresPermissions(value = "role:data:update")
    @ResponseBody
    public Object updateForJson(SysRole role) {
        SysRole db = roleService.findOne(role.getId());
        SysRole source = new SysRole();
        BeanUtils.copyProperties(db, source);
        SysRole result = roleService.updateRole(role);
        LoggerHelper.logInfo("修改角色‘{}’的信息{}", db.getRoleName(), new LoggerHelper.PropertyMerge(source, result)
                        .addPropertyDes("roleName", "角色名称")
                        .addPropertyDes("roleDesc", "角色描述")
        );
        return JsonFilter.doPropertyFilter(result, new PropertyCollection()
                .addProperties(SysRole.class, "id", "roleName"));
    }

    /**
     * ajax删除角色
     *
     * @param searchRoleCondition 角色id字符串,格式为： JsonList(eg:{"ids":["1","2","3"]})
     * @return 操作结果
     */
    @RequestMapping(value = "deleteForJson", method = RequestMethod.POST)
    @RequiresPermissions(value = "role:data:delete")
    @ResponseBody
    public Object deleteForJson(SearchRoleCondition searchRoleCondition) {
        List<SysRole> roles = roleService.deleteRole(searchRoleCondition.getIds());
        LoggerHelper.logInfo("删除了‘{}’", new LoggerHelper.PropertyReader<SysRole>(roles,
                "roleName"));
        return JsonFilter.doPropertyFilter(roles, new PropertyCollection()
                .addProperties(SysRole.class, "id", "roleName"));
    }

    /**
     * ajax分页查询角色
     *
     * @param pageNumber 当前页码
     * @param pageSize   每页显示条数
     * @param role       角色对象包含查询条件
     * @return 返回查询结果
     */
    @RequestMapping("queryPageForJson")
    @ResponseBody
    public Object queryPageForJson(
            @RequestParam(value = "page", required = false, defaultValue = "1") Integer pageNumber,
            @RequestParam(value = "rows", required = false, defaultValue = "10") Integer pageSize,
            SearchRoleCondition role) {
        role.setLikeWord(true);
        Page<SysRole> page = roleService.findAllByPage(role, PageUtils.buildPageRequest(pageNumber, pageSize, "createDate", "desc"));
        return JsonFilter.doPropertyFilter(page, new PropertyCollection()
                .addProperties(SysRole.class, "id", "roleName", "roleDesc", "available"));
    }

    /**
     * 角色树 用户选择角色
     *
     * @return List<TreeNode> 用户角色树
     */
    @RequestMapping("list")
    @ResponseBody
    public Object list(SearchRoleCondition searchRoleCondition) {
        return roleService.findAllByPage(searchRoleCondition, null).getContent();
    }
}
